// 前端应用主逻辑
class BreakfastApp {
    constructor() {
        this.userInfo = null;
        this.apiBase = 'http://localhost:3000/api';
        this.init();
    }

    async init() {
        await this.checkLoginStatus();
        this.setupEventListeners();
    }

    // 检查登录状态
    async checkLoginStatus() {
        const savedUserInfo = localStorage.getItem('userInfo');
        if (savedUserInfo) {
            this.userInfo = JSON.parse(savedUserInfo);
            this.showMainContent();
        } else {
            this.showLoginPage();
        }
    }

    // 微信登录
    async wechatLogin() {
        try {
            // 模拟微信登录流程
            const response = await fetch(`${this.apiBase}/wechat/login`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ code: 'mock_wx_code' })
            });

            const result = await response.json();
            
            if (result.success) {
                this.userInfo = { openid: result.openid };
                localStorage.setItem('userInfo', JSON.stringify(this.userInfo));
                
                if (result.isNewUser) {
                    this.showAllergenSetup();
                } else {
                    this.showMainContent();
                }
            }
        } catch (error) {
            console.error('登录失败:', error);
            alert('登录失败，请重试');
        }
    }

    // 设置过敏源
    async setAllergens(allergens) {
        try {
            const response = await fetch(`${this.apiBase}/user/set-allergens`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ 
                    openid: this.userInfo.openid, 
                    allergens 
                })
            });

            const result = await response.json();
            if (result.success) {
                this.showUserSettings();
            }
        } catch (error) {
            console.error('设置过敏源失败:', error);
        }
    }

    // 设置用户信息
    async setUserSettings(settings) {
        try {
            const response = await fetch(`${this.apiBase}/user/set-settings`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ 
                    openid: this.userInfo.openid, 
                    ...settings 
                })
            });

            const result = await response.json();
            if (result.success) {
                this.showMainContent();
            }
        } catch (error) {
            console.error('设置用户信息失败:', error);
        }
    }

    // AI生成菜单
    async generateAIMenu(timeConstraint, mealType) {
        try {
            const response = await fetch(`${this.apiBase}/ai/generate-menu`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ 
                    openid: this.userInfo.openid, 
                    timeConstraint, 
                    mealType 
                })
            });

            const result = await response.json();
            if (result.success) {
                this.displayAIMenu(result.menu);
            }
        } catch (error) {
            console.error('生成菜单失败:', error);
        }
    }

    // 显示页面
    showLoginPage() {
        document.getElementById('loginPage').style.display = 'block';
        document.getElementById('allergenPage').style.display = 'none';
        document.getElementById('settingsPage').style.display = 'none';
        document.getElementById('mainContent').style.display = 'none';
    }

    showAllergenSetup() {
        document.getElementById('loginPage').style.display = 'none';
        document.getElementById('allergenPage').style.display = 'block';
        document.getElementById('settingsPage').style.display = 'none';
        document.getElementById('mainContent').style.display = 'none';
    }

    // 跳过过敏源设置
    async skipAllergens() {
        try {
            // 保存空过敏源列表
            const response = await fetch(`${this.apiBase}/user/set-allergens`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    openid: this.userInfo.openid,
                    allergens: []
                })
            });

            if (response.ok) {
                this.showUserSettings();
            }
        } catch (error) {
            console.error('跳过过敏源设置失败:', error);
            this.showUserSettings(); // 即使API调用失败也继续
        }
    }

    showUserSettings() {
        document.getElementById('loginPage').style.display = 'none';
        document.getElementById('allergenPage').style.display = 'none';
        document.getElementById('settingsPage').style.display = 'block';
        document.getElementById('mainContent').style.display = 'none';
    }

    // 跳过敏源设置
    async skipSettings() {
        try {
            // 保存默认设置
            const response = await fetch(`${this.apiBase}/user/set-settings`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    openid: this.userInfo.openid,
                    age: 25,
                    gender: '未知',
                    dietaryPreferences: [],
                    healthGoals: []
                })
            });

            if (response.ok) {
                this.showMainContent();
            }
        } catch (error) {
            console.error('跳过设置失败:', error);
            this.showMainContent(); // 即使API调用失败也继续
        }
    }

    showMainContent() {
        document.getElementById('loginPage').style.display = 'none';
        document.getElementById('allergenPage').style.display = 'none';
        document.getElementById('settingsPage').style.display = 'none';
        document.getElementById('mainContent').style.display = 'block';
        this.loadDefaultRecipes();
    }

    // 设置事件监听
    setupEventListeners() {
        // 登录按钮
        document.getElementById('loginBtn').addEventListener('click', () => this.wechatLogin());
        
        // 过敏源设置
        document.getElementById('allergenForm').addEventListener('submit', (e) => {
            e.preventDefault();
            const allergens = Array.from(document.querySelectorAll('input[name="allergen"]:checked'))
                .map(input => input.value);
            this.setAllergens(allergens);
        });

        // 用户设置
        document.getElementById('settingsForm').addEventListener('submit', (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const settings = {
                age: formData.get('age'),
                gender: formData.get('gender'),
                dietaryPreferences: formData.getAll('dietaryPreference'),
                healthGoals: formData.getAll('healthGoal')
            };
            this.setUserSettings(settings);
        });

        // AI生成菜单
        document.getElementById('generateMenuBtn').addEventListener('click', () => {
            const time = document.getElementById('menuTime').value;
            const type = document.getElementById('menuType').value;
            this.generateAIMenu(time, type);
        });
    }

    // 加载默认食谱
    loadDefaultRecipes() {
        // 原有的食谱显示逻辑
        const recipes = [
            {
                id: 1,
                name: "香蕉燕麦粥",
                time: 5,
                category: "中式",
                ingredients: ["香蕉1根", "燕麦片50g", "牛奶200ml", "蜂蜜适量"],
                steps: "1. 香蕉压成泥\n2. 加入燕麦片和牛奶\n3. 微波炉加热2分钟\n4. 加入蜂蜜调味",
                nutrition: "富含膳食纤维和钾，低GI值"
            }
            // ... 其他食谱
        ];
        
        this.displayRecipes(recipes);
    }

    displayRecipes(recipes) {
        const container = document.getElementById('recipesContainer');
        container.innerHTML = recipes.map(recipe => `
            <div class="recipe-card">
                <h3>${recipe.name}</h3>
                <div>
                    <span class="recipe-time">${recipe.time}分钟</span>
                    <span class="recipe-category">${recipe.category}</span>
                </div>
                <div class="recipe-ingredients">
                    <strong>食材：</strong>${recipe.ingredients.join('、')}
                </div>
                <div class="recipe-steps">
                    <strong>步骤：</strong><br>${recipe.steps}
                </div>
                <div style="margin-top: 10px; color: #666;">
                    <strong>营养：</strong>${recipe.nutrition}
                </div>
            </div>
        `).join('');
    }

    displayAIMenu(menu) {
        const container = document.getElementById('aiMenuContainer');
        container.innerHTML = `
            <div class="ai-menu-card">
                <h3>🤖 AI定制推荐: ${menu.name}</h3>
                <div class="recipe-time">${menu.time}分钟 | ${menu.calories}卡路里</div>
                
                <div class="menu-details">
                    <div class="nutrition-facts">
                        <span>蛋白质: ${menu.protein}g</span>
                        <span>碳水: ${menu.carbs}g</span>
                        <span>脂肪: ${menu.fat}g</span>
                    </div>
                    
                    <div class="recipe-ingredients">
                        <strong>食材：</strong>${menu.ingredients.join('、')}
                    </div>
                    
                    <div class="recipe-steps">
                        <strong>步骤：</strong><br>
                        ${menu.steps.map((step, index) => `${index + 1}. ${step}`).join('<br>')}
                    </div>
                    
                    <div class="nutrition-highlight">
                        <strong>营养特点：</strong>${menu.nutrition}
                    </div>
                </div>
            </div>
        `;
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new BreakfastApp();
});